#!/usr/bin/env python
#import sip
#sip.setapi('QVariant', 2)

# From Statements

from PySide.QtCore import *
from PySide.QtGui import *

# Import Statements
import sys
import commonfunctions
import datahandler
import contenttab
import imagetab
import tabletab
import layouttab
import sectiontab
import examinertab
import casesettingstab
# import wombat_rc
"""
Note Types - notetype

1 - Content Note
2 - Image Note
3 - Table Note
"""
qt_app = QApplication(sys.argv)

# Main Application Class
class WombatApp(QMainWindow):
    def __init__(self):

        super(WombatApp, self).__init__()

        self.init()
        
    def init(self): 
        # global variables
        icon = QIcon(QDir.currentPath() + "/images/wombat_32.ico")
        # Initialize common functions class
        self.common = commonfunctions.CommonFunctions()
        # Initialize sqlite.data class
        self.data = datahandler.DataHandler()
        self.currentcaseid = None
        self.currentcasefile = None
        self.currentnoteid = None
        self.currentimageid = None
        self.currenttableid = None
        self.setMinimumSize(QSize(680, 480))
        self.setWindowTitle("Wombat")
        self.setWindowIcon(icon)
        
        self.mainStack = QStackedWidget()
        self.createStack = QTabWidget()
        self.manageStack = QTabWidget() # case information, examiner information, layout
        self.previewStack = QTabWidget() # case settings, publish settings, publish features
        self.bkgdLabel = QLabel("hi")
        self.bkgd = QImage(QDir.currentPath() + "/images/wombat_border_sm_solid.png")
        self.setCentralWidget(self.bkgdLabel)
        self.bkgdLabel.setPixmap(QPixmap.fromImage(self.bkgd))
        self.bkgdLabel.setAlignment(Qt.AlignCenter)
        self.bkgdLabel.setBackgroundRole(QPalette.Dark)
        
        # Create Layout Pieces
        self.createActions()
        self.createToolbar()

        self.stackManager = QStackedWidget()

        # Creation of "Create Content Stack"
        # use separate file and just import it here...
        self.contentTab = contenttab.CreateContentTab(self)
        self.imageTab = imagetab.CreateImageTab(self)
        self.tableTab = tabletab.CreateTableTab(self)
        # Creation of "Manage Stack"
        self.sectionTab = sectiontab.CreateSectionTab(self)
        self.layoutTab = layouttab.CreateLayoutTab(self)
        self.examinerTab = examinertab.CreateExaminerTab(self)
        # Creation of "Preview Stack"
        self.casesetTab = casesettingstab.CreateCaseSettingsTab(self)
        # Create Content Stack Tabs
        self.createStack.addTab(self.contentTab, "Create Text Notes")
        self.createStack.addTab(self.imageTab, "Import Image Notes")
        self.createStack.addTab(self.tableTab, "Create Table Notes")
        # Create Layout Stack Tabs
        self.manageStack.addTab(self.sectionTab, "Manage Sections")
        self.manageStack.addTab(self.layoutTab, "Manage Case Layout")
        self.manageStack.addTab(self.examinerTab, "Manage Examiners")
        # Create Preview Stack Tabs
        self.previewStack.addTab(self.casesetTab, "Manage Case Settings")

        self.stackManager.addWidget(self.createStack)
        self.stackManager.addWidget(self.manageStack)
        self.stackManager.addWidget(self.previewStack)
        
        # check if any cases exist in db, if they do, then enable the open cases toolbar button
        self.openCaseAction.setEnabled(self.data.sql(self.data.casesExist, None, 1))

    def createNewCaseFile(self):
        tmpcaseid = None
        tmpcasefile = None
        tmpcasefile, ok = QInputDialog.getText(self, "Universal Case File Number", "Enter the UCFN:")
        if ok and tmpcasefile:
        # add item to the db for a new casefile
            if self.data.sql(self.data.caseExist, [tmpcasefile], 1):
                self.common.displayError("Case Creation Error", "UCFN Already Exists. Open the existing case or create a different one.", "warning")
                tmpcaseid = -1
            else:
                # create case file since it does not exist
                tmpcaseid = self.data.sql(self.data.addNewCase, [tmpcasefile], 1)
        else:
            tmpcaseid = -1
        return tmpcaseid, tmpcasefile

    def newCase(self):
        # if no course is open... load new dialog:
        if self.currentcaseid is None or self.currentcaseid is -1:
            self.currentcaseid, self.currentcasefile = self.createNewCaseFile()
            if self.currentcaseid is not None and self.currentcaseid is not -1:
                self.setWindowTitle("Wombat - " + self.currentcasefile)
                self.createStackAction.setEnabled(True)
                self.organizeStackAction.setEnabled(True)
                self.publishStackAction.setEnabled(True)
            elif self.currentcaseid is None:
                self.common.displayError("Case Creation Error", "1.0 New Case Creation Failed.  Please try again and if the error continues, send a bug report.", "critical")
        else: # course already open
            self.checkMessage = QMessageBox.warning(self, "Case is Open", "A case is already open.\n Are you sure you want to close the open case and create a new one?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if self.checkMessage is QMessageBox.StandardButton.Yes:
                self.currentcaseid, self.currentcasefile = createNewCaseFile()
                if self.currentcaseid is not None:
                    self.setWindowTitle("Wombat - " + self.currentcasefile)
                    self.resetStackWidgetValues()
                    if not self.createStackAction.isEnabled():
                        self.createStackAction.setEnabled(True)
                    if not self.organizeStackAction.isEnabled():
                        self.organizeStackAction.setEnabled(True)
                    if not self.publishStackAction.isEnabled():
                        self.publishStackAction.setEnabled(True)
                else:
                    self.common.displayError("Case Creation Error", "1.1 New Case Creation Failed. Please try again and if the error continues, send a bug report.", "critical")

    def openCaseFile(self):
        tmpcasefilelist = None
        tmpcasefilelist = self.data.sql(self.data.getCaseFileList, None, 1)
        if tmpcasefilelist is not None:
            tmpcasefile, ok = QInputDialog.getItem(self, "Open Existing Case File", "Select Case to Open:", tmpcasefilelist, 0, False)
            if ok and tmpcasefile:
                # get info for selected case
                tmpcasedata = self.data.sql(self.data.getCaseData, [tmpcasefile], 1)
                return tmpcasedata[0], tmpcasedata[1]
            else:
                return None, None

    def openCase(self):
        # check if a course is open
        if self.currentcaseid is None or self.currentcaseid is -1:
            self.currentcaseid, self.currentcasefile = self.openCaseFile()
            if self.currentcaseid is not None and self.currentcaseid is not -1:
                self.setWindowTitle("Wombat - " + self.currentcasefile)
                if not self.createStackAction.isEnabled():
                    self.createStackAction.setEnabled(True)
                if not self.organizeStackAction.isEnabled():
                    self.organizeStackAction.setEnabled(True)
                if not self.publishStackAction.isEnabled():
                    self.publishStackAction.setEnabled(True)
                else:
                    self.common.displayError("Case Open Error", "2.0 Open Case Failed. Please try again and if the error continues, send a bug report.", "critical")
        else: # course is open
            self.checkmessage = QMessageBox.warning(self, "Case is Open", "A case is already open.\n Are you sure you want to close the open case and create a new one?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if self.checkmessage is QMessageBox.StandardButton.Yes:
                self.currentcaseid, self.currentcasefile = self.openCaseFile()
                if self.currentcaseid is not None:
                    self.setWindowTitle("Wombat - " + self.currentcasefile)
                    self.resetStackWidgetValues()
                    if not self.createStackAction.isEnabled():
                        self.createStackAction.setEnabled(True)
                else:
                    self.common.displayError("Case Open Error", "2.1 Open Case Failed. Please try again and if the error continues, send a bug report.", "critical")

    def manageSelectedStack(self):
        for tmpstack in [self.createStackAction, self.organizeStackAction, self.publishStackAction]:
            tmpstack.setChecked(False)
        self.sender().setChecked(True)
        self.setCentralWidget(self.stackManager)
        if self.sender() is self.createStackAction:
            self.stackManager.setCurrentWidget(self.createStack)
            self.contentTab.updateNoteListSql()
            self.imageTab.updateImageList()
            self.tableTab.updateTableList()
        elif self.sender() is self.organizeStackAction:
            self.stackManager.setCurrentWidget(self.manageStack)
            self.layoutTab.updateLists()
            self.sectionTab.updateLists()
            self.examinerTab.updateLists()
        elif self.sender() is self.publishStackAction:
            self.stackManager.setCurrentWidget(self.previewStack)
            self.casesetTab.getSettings()
        else:
            self.common.displayError("Invalid Stack", "An Invalid Stack was selected. If this continues, please file a bug report.", "warning")

    def resetStackWidgetValues(self):
        self.contentTab.noteEditor.setHtml("") # clear editor content as well as undo/redo for new caseid
        self.contentTab.updateNoteListSql() # reset noteList for new caseid
        self.imageTab.updateImageList() # clear imagelist and imageviewer
        self.tableTab.updateTableList() # clear tablelist and tableeditor
        self.layoutTab.updateLists() # clear and reset all 3 lists
        self.sectionTab.updateLists() # clear and reset all 2 section lists
        self.examinerTab.updateLists() # clear and reset all 2 examiner lists
        self.casesetTab.clearSettings() # clear settings of existing course values

    def manageTabChanged(self):
        if self.manageStack.currentWidget() is self.layoutTab:
            self.layoutTab.updateLists()

    def createActions(self):
        self.newCaseAction = QAction(QIcon(QDir.currentPath() + "/images/document-new.png"), "New Case Notes", self)
        self.openCaseAction = QAction(QIcon(QDir.currentPath() + "/images/document-open.png"), "Open Case Notes", self)
        # check if any cases exist, if not, disable open case button.
        self.createStackAction = QAction(QIcon(QDir.currentPath() + "/images/accessories-text-editor.png"), "Manage Case Content", self)
        self.organizeStackAction = QAction(QIcon(QDir.currentPath() + "/images/x-office-address-book.png"), "Manage Case Structure", self)
        self.publishStackAction = QAction(QIcon(QDir.currentPath() + "/images/package-x-generic.png"), "Publish Content", self)
        self.createStackAction.setCheckable(True)
        self.createStackAction.setChecked(False)
        self.createStackAction.setEnabled(False)
        self.organizeStackAction.setCheckable(True)
        self.organizeStackAction.setChecked(False)
        self.organizeStackAction.setEnabled(False)
        self.publishStackAction.setCheckable(True)
        self.publishStackAction.setChecked(False)
        self.publishStackAction.setEnabled(False)
        self.newCaseAction.triggered.connect(self.newCase)
        self.openCaseAction.triggered.connect(self.openCase)
        self.createStackAction.triggered[bool].connect(self.manageSelectedStack)
        self.organizeStackAction.triggered[bool].connect(self.manageSelectedStack)
        self.publishStackAction.triggered[bool].connect(self.manageSelectedStack)
        self.manageStack.currentChanged.connect(self.manageTabChanged)

    def createToolbar(self):
        self.mainToolbar = self.addToolBar("")
        self.mainToolbar.addAction(self.newCaseAction)
        self.mainToolbar.addAction(self.openCaseAction)
        self.mainToolbar.addSeparator()
        self.mainToolbar.addAction(self.createStackAction)
        self.mainToolbar.addAction(self.organizeStackAction)
        self.mainToolbar.addAction(self.publishStackAction)
        self.mainToolbar.setMovable(False)

    def run(self):
        self.show()
        qt_app.exec_()
    
app = WombatApp()
icon = QIcon("./images/wombat_32.ico")
app.setWindowIcon(icon)
app.run()
